﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using WinnerCMS.BLL;
using WinnerCMS.Common;
using WinnerCMS.Model;

namespace WinnerCMS.HttpModule
{

    public class IpFilter : System.Web.IHttpModule
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public IpFilter()
        {

        }
        public void Dispose() { }

        public void Init(HttpApplication app)
        {
            //建立安全模块 
            app.AcquireRequestState += (this.AcquireRequestState);

        }
        /// <summary>
        /// 被控制的后缀名
        /// </summary>
        private readonly static string[] Suffixs = { ".aspx", ".htm", ".html" };

        private void AcquireRequestState(object o, EventArgs e)
        {
            HttpApplication app = o as HttpApplication;
            HttpContext context = app.Context;

            string path = context.Request.Path;


            if (!Suffixs.Any(x => path.EndsWith(x, StringComparison.CurrentCultureIgnoreCase)))
            {
                return;
            }

            if (path.IndexOf("error.aspx", StringComparison.CurrentCultureIgnoreCase) > -1)
            {
                return;
            }

            IList<IPBlackList> ipBlackList = IPBlackListManage.GetBlackList();

            if (ipBlackList.Any() == false) return;

            long lip = IP2Location.IpToInt(HttpClient.GetIP(context));


            if (ipBlackList.Any(x => x.SectorStart <= lip && lip <= x.SectorEnd))
            {
                context.Response.StatusCode = 404;
                context.Response.SuppressContent = true;
                context.Response.End();
            }

        }
    }
}